<template>
  <div class="tag-import">
    <tag-step :step="step" :active="config.stepNumber"></tag-step>
    <div class="drawer-wrap">
      <div class="drawer-content tag-scrollbar">
        <div v-if="config.stepNumber === 0" class="upload-page">
          <tag-upload
            ref="fileUpload"
            drag
            :fileList="upload.fileList"
            @uploadFun="fileFun"
            @removeFun="fileRemove"
            :fileLimit="upload.fileLimit"
          >
            <template #tip>
              只能上传对应的模板文件，一次导入只能上传一个文件
            </template>
          </tag-upload>
        </div>
        <div v-if="config.stepNumber === 1 || config.stepNumber === 2" class="table-page">
          <tag-content-header search setting @toolFun="toolFun" :settingData="columns">
            <template #title>
              <span v-if="config.stepNumber === 1"
                >附件共有<span class="data-count data-normal">{{ importData.all }}</span
                >条记录数，初步导入成功<span class="data-count data-success">{{ importData.success }}</span
                >条，导入失败<span class="data-count data-faild">{{ importData.faild }}</span
                >条，导入成功率<span class="data-count data-success">{{ importData.rate }}</span
                >，点击“下一步”校验数据</span
              >
              <span v-if="config.stepNumber === 2"
                >在导入成功<span class="data-count data-normal">{{ importData.success }}</span
                >条记录数中，校验通过<span class="data-count data-success">{{ checkData.success }}</span
                >条，校验不通过<span class="data-count data-faild">{{ checkData.faild }}</span
                >条，校验通过率<span class="data-count data-success">{{ checkData.rate }}</span
                >，点击“下一步”确认校验结果</span
              >
            </template>
          </tag-content-header>
          <tag-table
            ref="table"
            @refresh="getList"
            :data="dataList"
            :loading="loading"
            :columns="columns"
            :params="params"
            :total="totalSize"
          >
            <template #operation="{ scope }">
              <div class="operation-button-box">
                <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                  <icon-svg name="iconDelete" class="svg-delete" @click.native="handleDelete(scope.row)"></icon-svg>
                </el-tooltip>
              </div>
            </template>
          </tag-table>
        </div>
        <div v-if="config.stepNumber === 3" class="save-page data-normal">
          <p>数据完成检验。</p>
          <p>
            附件共有<span class="data-count">{{ importData.all }}</span
            >条记录数，导入成功<span class="data-count data-success">{{ importData.success }}</span
            >条，导入失败<span class="data-count data-faild">{{ importData.faild }}</span
            >条，导入成功率<span class="data-count data-success">{{ importData.rate }}</span
            >。
          </p>
          <p>
            在导入成功记录数中，校验通过<span class="data-count data-success">{{ checkData.success }}</span
            >条，校验不通过<span class="data-count data-faild">{{ checkData.faild }}</span
            >条（校验不通过的数据将不会被保存），校验通过率<span class="data-count data-success">{{
              checkData.rate
            }}</span
            >。
          </p>
          <p v-if="extraData.uncertainNumber || extraData.certainNumber">
            在导入成功记录数中，部门审核阶段有<span class="data-count data-success">{{
              extraData.uncertainNumber
            }}</span
            >条。
          </p>
          <p>
            请点击“{{ type === 1 || type === 2 ? '保存或提交' : '确定' }}”按钮保存校验通过的数据。如果未点击“{{
              type === 1 || type === 2 ? '保存或提交' : '确定'
            }}”按钮，则数据将不会被保存。
          </p>
        </div>
      </div>
    </div>
    <tag-user ref="tagUser" batch :procId="type" :nodeId="nodeId" @callback="handleSubmit"></tag-user>
  </div>
</template>

<script>
import tagUser from './tag-user-selection'
import { Loading } from 'element-ui'
let saveUrl = 'stg/stgStdFile/import/save'
let submitUrl = ''
let previewUrl = 'stg/stgStdFile/import/excel'
export default {
  name: 'tag-import',
  props: {
    type: {
      required: true
    },
    nodeId: {
      type: Number,
      required: false,
      default: 0
    },
    closeAfterSave: {
      type: Boolean,
      default: true
    },
    hasSimilar: {
      type: Boolean,
      default: false
    },
    config: {
      type: Object,
      default: () => {
        return { stepNumber: 0, error: false, previewUrl: previewUrl, saveUrl: saveUrl, submitUrl: submitUrl }
      }
    }
  },
  components: {
    tagUser
  },
  data() {
    return {
      loading: false,
      step: [
        {
          icon: 'iconUpload',
          name: '上传数据'
        },
        {
          icon: 'iconPreview',
          name: '预览数据'
        },
        {
          icon: 'iconReview',
          name: '校验数据'
        },
        {
          icon: 'iconSave',
          name: '保存数据'
        }
      ],
      dataList: [],
      columns: [],
      params: {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      },
      totalSize: 0,
      upload: {
        fileId: '',
        fileList: [],
        fileLimit: {
          type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          typeMsg: '只能上传excel文件'
        }
      },
      batchId: '',
      importData: {
        all: 0,
        success: 0,
        faild: 0,
        rate: '0%'
      },
      checkData: {
        success: 0,
        faild: 0,
        rate: '0%'
      },
      extraData: {
        certainNumber: 0,
        uncertainNumber: 0
      },
      batchLoading: null
    }
  },
  watch: {
    loading(val) {
      if (val) {
        this.batchLoading = Loading.service({
          target: '.batch-drawer .el-drawer__body',
          spinner: 'el-icon-loading',
          customClass: 'tag-import-loading'
        })
      } else {
        this.batchLoading.close()
        this.batchLoading = null
      }
    }
  },
  methods: {
    getList() {
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl('stg/stgStdFile/import/records'),
        method: 'get',
        params: this.$ajax.setParams(this.getParams())
      }).then(({ data }) => {
        if (data && data.code === '0') {
          if (data.data.currentPageNum === this.params.currentPageNum) {
            this.setColumns(data.data.columnNames)
            this.dataList = data.data.records
            this.totalSize = data.data.totalSize
          }
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    getParams() {
      let params = Object.assign({}, this.params, {
        batchId: this.batchId,
        tmplId: this.type,
        validated: this.config.stepNumber === 2,
        conditions: this.getConditions(),
        d: true
      })
      return params
    },
    getConditions() {
      let list = []
      Object.keys(this.params.queryParams).forEach(item => {
        list.push({
          columnName: item,
          useLike: item !== 'dqc_error',
          value: this.params.queryParams[item]
        })
      })
      return list
    },
    setColumns(data) {
      if (this.columns.length !== data.length) {
        let columns = []
        if (this.columns.length === 0) {
          data.forEach((item, index) => {
            let param = {
              show: index < 6,
              label: item.columnCname,
              prop: item.columnEname,
              search: true,
              searchKey: '',
              align: 'center'
            }
            if (item.columnEname === 'dqc_error') {
              param.searchType = 'select'
              param.searchList = [{ key: '通过', value: '通过' }, { key: '不通过', value: '不通过' }]
            }
            columns.push(param)
          })
        } else {
          // for (var i = data.length - 2; i < data.length; i++) {
          for (var i = 0; i < data.length; i++) {
            if (!this.columns.find(v => v.prop === data[i].columnEname)) {
              let param = {
                show: true,
                label: data[i].columnCname,
                prop: data[i].columnEname,
                search: true,
                searchKey: '',
                tooltip: i !== data.length - 1,
                align: 'center'
              }
              if (data[i].columnEname === 'dqc_error') {
                param.searchType = 'select'
                param.searchList = [{ key: '通过', value: '通过' }, { key: '不通过', value: '不通过' }]
              }
              columns.push(param)
            }
          }
          columns = this.columns.concat(columns)
        }
        if (this.config.stepNumber === 2 && (this.type === 1 || this.type === 2)) {
          if (!this.columns.find(v => v.prop === 'operation')) {
            columns.push({
              show: 'fixed',
              label: '操作',
              prop: 'operation',
              align: 'center',
              width: 50
            })
          }
        }
        this.columns = columns
      }
    },
    next() {
      if (this.loading) {
        this.$alert('请等待加载完成')
        return
      }
      let step = this.config.stepNumber
      if (step === 0 && !this.upload.fileId) {
        this.$alert('请先上传需要导入的文件')
        return
      }
      switch (step) {
        case 0:
          this.config.stepNumber = step + 1
          this.getPreviewList()
          break
        case 1:
          this.config.stepNumber = step + 1
          this.getCheckList()
          break
        case 2:
          this.config.stepNumber = step + 1
          break
        case 3:
          this.save()
          break
      }
    },
    back() {
      if (this.config.stepNumber !== 3) return
      this.config.stepNumber = 2
    },
    getPreviewList() {
      this.params.currentPageNum = 1
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl(this.config.previewUrl ? this.config.previewUrl : previewUrl),
        method: 'post',
        data: this.$ajax.setData({
          fileId: this.upload.fileId,
          tmplId: this.type
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.batchId = data.data.batchId
          this.importData.all = data.data.recordNumber
          this.importData.success = data.data.successNumber
          this.importData.faild = data.data.failNumber
          this.importData.rate = data.data.successRate
          this.getList()
        } else {
          this.$message.error(data.data || data.msg)
          this.config.error = true
        }
        this.loading = false
      })
    },
    getCheckList() {
      this.params.currentPageNum = 1
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl(this.hasSimilar ? 'ast/astTagRequire/validate' : 'stg/stgStdFile/import/validate'),
        method: 'post',
        data: this.$ajax.setData({
          batchId: this.batchId,
          tmplId: this.type
        }),
        timeout: 0
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.checkData.success = data.data.successNumber
          this.checkData.faild = data.data.failNumber
          this.checkData.rate = data.data.successRate
          if (data.data.certainNumber) this.extraData.certainNumber = data.data.certainNumber
          if (data.data.uncertainNumber) this.extraData.uncertainNumber = data.data.uncertainNumber
          this.getList()
        } else {
          this.$message.error(data.data || data.msg)
          this.config.error = true
        }
        this.loading = false
      })
    },
    save() {
      this.loading = true
      this.$ajax({
        url: this.$ajax.setUrl(this.config.saveUrl ? this.config.saveUrl : saveUrl),
        method: 'post',
        data: this.$ajax.setData({
          batchId: this.batchId,
          tmplId: this.type
        }),
        timeout: 0
      })
        .then(({ data }) => {
          if (data && data.code === '0') {
            this.$message.success(data.msg)
            if (this.closeAfterSave) this.$emit('close')
          } else {
            this.$message.error(data.data || data.msg)
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    submit(needHandler = true) {
      this.loading = true
      if (needHandler) this.$refs.tagUser.showDialog()
      else this.bathSubmit()
    },
    bathSubmit() {
      this.$ajax({
        url: this.$ajax.setUrl(`${this.config.submitUrl}/${this.batchId}`),
        method: 'post',
        data: this.$ajax.setData(),
        timeout: 0
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.$message.success(data.msg)
          this.$emit('close')
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    handleSubmit(handlerId) {
      if (handlerId) {
        this.$ajax({
          url: this.$ajax.setUrl(`${this.config.submitUrl}/${this.batchId}/${handlerId}`),
          method: 'post',
          data: this.$ajax.setData(),
          timeout: 0
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.$message.success(data.msg)
            this.$emit('close')
          } else {
            this.$message.error(data.data || data.msg)
          }
          this.loading = false
        })
      } else {
        this.loading = false
      }
    },
    fileFun(params) {
      this.upload.fileId = params.fileId
      this.upload.fileList = params.fileList.slice(-1)
    },
    fileRemove() {
      this.upload.fileId = ''
    },
    toolFun(operation) {
      switch (operation) {
        case 'search':
          // 搜索动作
          this.$refs['table'].searchToggle()
          break
        case 'refresh':
          // 刷新动作
          this.getList()
          break
      }
    },
    removeTable() {
      this.$ajax({
        url: this.$ajax.setUrl(`stg/stgStdFile/import/deleteBatchRecords/${this.type}/${this.batchId}`),
        method: 'delete',
        params: this.$ajax.setParams()
      }).then(() => {})
      this.$ajax({
        url: this.$ajax.setUrl('stg/stgFileUpload/' + this.upload.fileId),
        method: 'delete',
        params: this.$ajax.setParams()
      }).then(() => {})
    },
    handleDelete(scope) {
      this.$confirm(`确定删除【${scope[this.columns[0].prop]}】`).then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        this.$ajax({
          url: this.$ajax.setUrl(`ast/astTagRequireManager/deleteRecords/${this.type}/${scope.tag_id}`),
          method: 'delete',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.$message.success(data.msg)
            this.getList()
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      })
    },
    reset() {
      if (this.batchId) {
        this.removeTable()
      }
      this.loading = false
      this.dataList = []
      this.columns = []
      this.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.totalSize = 0
      this.upload.fileId = ''
      this.upload.fileList = []
      this.batchId = ''
      this.importData = {
        all: 0,
        success: 0,
        faild: 0,
        rate: '0%'
      }
      this.checkData = {
        success: 0,
        faild: 0,
        rate: '0%'
      }
      this.extraData = {
        certainNumber: 0,
        uncertainNumber: 0
      }
    }
  }
}
</script>

<style lang="scss">
.tag-import {
  .tag-content-header {
    padding: 10px 20px 0;
    .title-box {
      float: none;
      height: auto;
      & > span {
        padding: 0;
      }
      span {
        &:before {
          display: none;
        }
      }
      .data-count {
        font-size: 25px;
        padding: 0 5px;
        vertical-align: inherit;
      }
    }
  }
  .upload-page {
    padding: 60px 0;
    text-align: center;
  }
  .table-page {
    padding: 20px 0;
  }
  .save-page {
    padding: 30px 0;
    p {
      padding: 10px 0;
    }
  }
  .data-count {
    font-size: 25px;
    padding: 0 5px;
  }
  .data-normal {
    color: #309ffa;
  }
  .data-success {
    color: $tag-green;
  }
  .data-faild {
    color: $tag-red;
  }
  .operation-button-box .el-icon-delete {
    color: $tag-red;
  }
}
</style>
